package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SmsService;
import com.itheima.health.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@DubboService
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    SmsService smsService;

    @Override
    public void sendValidateCode(String type, String telephone) {
        SecureRandom secureRandom = new SecureRandom();
        int validateCode = (int) (secureRandom.nextDouble() * 8999 + 1000);

        //redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + type + "_" + telephone).set(validateCode, 30, TimeUnit.SECONDS);
        smsService.send(type,telephone,validateCode+"");
        log.info("【验证码已发送】" + validateCode);
    }

    @Override
    public Boolean checkCode(String type, String telephone, String validateCode) {
        String code = (String) redisTemplate.opsForValue().get(RedisConst.VALIDATE_CODE_PRE + type + "_" + telephone);
        if (validateCode.equals(code)) {
            return true;
        }
        return null;
    }


}
